﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Windows.Media.Imaging;
using System.Drawing.Imaging;

public static class BitmapExtension
{
    /// <summary>
    /// Bitmap转BitmapSource
    /// </summary>
    /// <param name="bitmap"></param>
    /// <param name="formats">默认值ImageFormats.Jpeg</param>
    /// <returns></returns>
    public static BitmapSource ToBitmapSource(this Bitmap bitmap, ImageFormats formats = ImageFormats.Jpeg)
    {
        using (MemoryStream stream = new MemoryStream())
        {

            bitmap.Save(stream, (ImageFormat)new ImageFormatConverter().ConvertFromString(formats.ToString()));

            stream.Position = 0;
            BitmapImage result = new BitmapImage();
            result.BeginInit();
            // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
            // Force the bitmap to load right now so we can dispose the stream.
            result.CacheOption = BitmapCacheOption.OnLoad;
            result.StreamSource = stream;
            result.EndInit();
            result.Freeze();
            return result;
        }
    }
}